package com.example.cinema;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.widget.NestedScrollView;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.cinema.adapter.CommentAdapter;
import com.example.cinema.adapter.ShortCommentAdapter;
import com.example.cinema.bindingdata.CommentShortData;
import com.example.cinema.bindingdata.FollowFansData;
import com.example.cinema.bindingdata.ShortBindingData;
import com.example.cinema.bindingdata.UserInfoData;
import com.example.cinema.databinding.FragmentBlank3Binding;
import com.example.cinema.databinding.NavhanderViewBinding;
import com.example.cinema.drawview.ShortPlayerVideo;
import com.example.cinema.request.RequestData;
import com.example.cinema.request.RequestSend;
import com.example.cinema.testdara.TestData;
import com.example.cinema.toolclass.SvgaUtils;
import com.google.android.material.navigation.NavigationView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BlankFragment3#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BlankFragment3 extends Fragment  {

    @Override
    public void onResume() {
        super.onResume();
        startSvga();
        isvis();
        if(playerVideo!=null)
        {
            playerVideo.Playstart();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if(playerVideo!=null)
        {
            playerVideo.Playstop();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if(playerVideo!=null)
        {
            playerVideo.Playstop();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if(playerVideo!=null)
        {
            playerVideo.Playrelease();
        }
    }

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public BlankFragment3() {
        // Required empty public constructor

    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BlankFragment3.
     */
    // TODO: Rename and change types and number of parameters
    public static BlankFragment3 newInstance(String param1, String param2) {
        BlankFragment3 fragment = new BlankFragment3();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    private static FragmentBlank3Binding  FBB;
    private static boolean isinit;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if(!isinit)
        {
            FBB = DataBindingUtil.inflate(inflater,R.layout.fragment_blank3,container,false);
        }
        if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
        {
            View view = container.getRootView();
            view.setSystemUiVisibility(View.GONE);
        }else if(Build.VERSION.SDK_INT>=19){
            View view = container.getRootView();
            int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
            view.setSystemUiVisibility(UIOP);
        }

        return FBB.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        if(!isinit)
        {
            isinit = true;
            init();
            isvis();

        }

    }
    private UserAttribute attribute;
    private void isvis()
    {
        attribute = (UserAttribute) getActivity().getApplication();
        if(attribute.getUID()==null || attribute.getToken()==null)
        {
            FBB.mask.setVisibility(View.VISIBLE);
        }else {
            UserInfoData infoData = new UserInfoData();
            infoData.userimg.set(attribute.getUimage());
            infoData.userfans.set(attribute.getFans()+"");
            infoData.userfollow.set(attribute.getFollow()+"");
            infoData.userlove.set(attribute.getLove()+"");
            infoData.useralias.set(attribute.getUalias());
            infoData.usersid.set(attribute.getUID());
            infoData.userfree.set(String.valueOf(attribute.getFree()));
            infoData.usertime.set(attribute.getViptime());
            infoData.uservipstate.set(attribute.isVipbool());
            infoData.username.set(attribute.getUname());
            infoData.userworks.set(attribute.getUserworks());
            FBB.setInfodata(infoData);
            FBB.mask.setVisibility(View.GONE);
            FBB.follows.setChecked(true);

            View view = FBB.navigations.getHeaderView(0);
            NavhanderViewBinding nvb = DataBindingUtil.bind(view);
            nvb.setInfodata(infoData);
        }
    }
    private void startSvga()
    {
        SvgaUtils svgaUtils = new SvgaUtils(getContext(),FBB.svgaimg);
        svgaUtils.init();
        svgaUtils.startAnimator("txka");
    }


    private int page = 1;
    private int limit= 30;
    private List<FollowFansData> fansData = new ArrayList<>();
    private CommentAdapter commentAdapter;
    private int types;
    private void init() {
        attribute = (UserAttribute) getActivity().getApplication();

        commentAdapter = new CommentAdapter(getContext(), fansData, R.layout.followfans_item, BR.fdatas);
        FBB.gridview.setAdapter(commentAdapter);



        FBB.drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

        Menu menu = FBB.navigations.getMenu();
        Log.i("DKDS", attribute.getAppMode() + "");
        Log.i("DKDS", attribute.getAppMoneyMode() + "");


        FBB.rolltext.start();




        //打开侧滑
        FBB.seting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FBB.drawer.openDrawer(Gravity.LEFT);
            }
        });

        //操作列点击事件
        FBB.navigations.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int id = item.getItemId();
                Intent intent = new Intent();
                switch (id)
                {

                    case R.id.wor://作品列表
                        if(attribute.getToken()==null)
                        {
                            intent.setAction("sign");
                        }else {
                            intent.setAction("works");
                        }

                        break;
                    case R.id.kefu://客服

                        Toast.makeText(getContext(),"客服暂不在线可联系QQ"+attribute.getQQtext(),Toast.LENGTH_LONG).show();
                        return true;
                    case R.id.pswd://修改密码
                        if(attribute.getToken()==null)
                        {
                            intent.setAction("sign");
                        }else {
                            intent.setAction("password");
                        }
                        break;
                    case R.id.chongz://充值卡充值
                        if(attribute.getToken()==null)
                        {
                            intent.setAction("sign");
                        }else {
                            intent.setAction("cartpay");
                        }
                        break;
                }
                startActivity(intent);
                return true;
            }
        });

        //拦截点击
        FBB.mask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        //注册
        FBB.post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("userpost");
                startActivity(intent);
            }
        });
        //登录
        FBB.sign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("sign");
                startActivity(intent);
            }
        });
        //选择
        FBB.seleradio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId)
                {
                    case R.id.follows:
                        page = 1;
                        types = 1;
                        fansData.clear();
                        GetDatas(1);
                        break;
                    case R.id.fanss:
                        page = 1;
                        types = 0;
                        GetDatas(0);
                        fansData.clear();
                        break;
                }
            }
        });
        //点击查看
        FBB.gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                showDialog(fansData.get(position));
            }
        });
        //滚动
        FBB.scroll.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                int layheith = v.getChildAt(0).getMeasuredHeight();
                int cruheith = v.getMeasuredHeight();
                if(scrollY==(layheith-cruheith))
                {
                    page++;
                    Log.i("WWDAS","到底了"+page);
                    GetDatas(types);
                }
            }
        });
    }
    //打开选择视频
    private AlertDialog alertDialog;
    private ShortPlayerVideo playerVideo;
    private TextView viptv;
    private void showDialog(FollowFansData data)
    {
        int w = getResources().getDisplayMetrics().widthPixels;
        int h = getResources().getDisplayMetrics().heightPixels;

        ShortBindingData shortdata = new ShortBindingData();
        shortdata.image.set(data.image.get());
        shortdata.imgurl.set(data.uimge.get());
        shortdata.title.set(data.userm.get());
        Log.i("QQQS",data.image.get());
        Log.i("QQQS",data.uimge.get());
        videoid = data.videoid.get();
        Log.i("QQQS",videoid);

        ViewDataBinding viewDataBinding = DataBindingUtil.inflate(LayoutInflater.from(getActivity()),R.layout.short_video_user,null,false);
        viewDataBinding.setVariable(BR.mydata,shortdata);
        ImageView img = viewDataBinding.getRoot().findViewById(R.id.follow);
        img.setVisibility(View.GONE);
        playerVideo = viewDataBinding.getRoot().findViewById(R.id.player);
        View comment = viewDataBinding.getRoot().findViewById(R.id.comment);

        viptv = viewDataBinding.getRoot().findViewById(R.id.vipvideo);

        //完整观看
        viptv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("SQQQQ","VIP[[[[");
                new Thread(){
                    @Override
                    public void run() {
                        RequestData requestData = new RequestData(getContext());
                        String url = requestData.GetVipUrl(videoid,attribute);
                        if(url!=null)
                        {
                            Message message = new Message();
                            message.obj = url;
                            message.what = 1002;
                            handler.sendMessage(message);
                        }
                    }
                }.start();


            }
        });
        //评价点击
        comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cmmentdata.clear();
                GetComment();
                commentdata();
            }
        });

        viewDataBinding.getRoot().findViewById(R.id.playys).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playerVideo.Playrelease();
                alertDialog.cancel();
            }
        });


        alertDialog = new AlertDialog.Builder(getActivity()).setView(viewDataBinding.getRoot()).create();
        alertDialog.show();
        alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
                {
                    View view = FBB.gridview;
                    view.setSystemUiVisibility(View.GONE);
                }else if(Build.VERSION.SDK_INT>=19){
                    View view = FBB.gridview;
                    int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
                    view.setSystemUiVisibility(UIOP);
                }
            }
        });
        Window window = alertDialog.getWindow();
        window.getDecorView().setPadding(0,0,0,0);
        window.getDecorView().setBackgroundColor(Color.BLACK);
        WindowManager.LayoutParams wparams = window.getAttributes();
        wparams.width = w;
        wparams.height= h;
        wparams.gravity = Gravity.CENTER;
        window.setAttributes(wparams);


        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.height = h;
        params.width = w;
        params.gravity = Gravity.CENTER;
        playerVideo.setLayoutParams(params);
        playerVideo.setImgUrl(data.image.get());
        playerVideo.setPlayurl(data.shorturl.get());
        playerVideo.loadVideo();

        alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                playerVideo.Playrelease();
            }
        });
        if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
        {
            View view = FBB.gridview;
            view.setSystemUiVisibility(View.GONE);
        }else if(Build.VERSION.SDK_INT>=19){
            View view = FBB.gridview;
            int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
            view.setSystemUiVisibility(UIOP);
        }
    }

    //获取关注数据
    private void GetDatas(int type)
    {
        new Thread(){
            @Override
            public void run() {
                RequestData requestData = new RequestData(getContext());
                List<FollowFansData> data = requestData.GetFollowFansData(page,limit,attribute,type);
                Log.i("WWDAS","获得数量"+data.size());
                fansData.addAll(data);
                handler.sendEmptyMessage(1000);
            }
        }.start();
    }

    //获取评论数据
    private int cp =1;
    private int cl =30;
    private String videoid;
    private List<CommentShortData> cmmentdata = new ArrayList<>();
    private void GetComment()
    {
        new Thread(){
            @Override
            public void run() {
                RequestData requestData = new RequestData(getContext());
                List<CommentShortData> data = requestData.GetShortComment(videoid,cp,cl);
                cmmentdata.addAll(data);
                handler.sendEmptyMessage(1002);
            }
        }.start();
    }
    //弹出评论区
    private AlertDialog dialog;
    private ShortCommentAdapter scadapter;
    private EditText editText;
    private void commentdata()
    {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.comment_dialog,null);
        dialog = new AlertDialog.Builder(getContext())
                .setView(view)
                .create();
        ListView listView = view.findViewById(R.id.commentlist);
        scadapter = new ShortCommentAdapter(getContext(),cmmentdata,R.layout.comment_item);
        listView.setAdapter(scadapter);
        dialog.show();
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
                {
                    View view = FBB.gridview;
                    view.setSystemUiVisibility(View.GONE);
                }else if(Build.VERSION.SDK_INT>=19){
                    View view = FBB.gridview;
                    int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
                    view.setSystemUiVisibility(UIOP);
                }
            }
        });
        int width = getResources().getDisplayMetrics().widthPixels;
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.getDecorView().setMinimumWidth(width);
        window.getDecorView().setPadding(0,0,0,0);
        window.getDecorView().setBackgroundResource(R.drawable.dialog_round_bag);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width =width;
        params.height= WindowManager.LayoutParams.WRAP_CONTENT;
        window.setWindowAnimations(R.style.dialoganim);
        window.setAttributes(params);
        //评论点赞
        scadapter.SetZanListener(new ShortCommentAdapter.OnZanListener() {
            @Override
            public void ZanClick(ImageView view, int positon, Object data) {
                view.getDrawable().setLevel(2);
                RequestSend requestSend = new RequestSend(getContext());
                CommentShortData shortData = (CommentShortData) data;
                new Thread()
                {
                    @Override
                    public void run() {
                        boolean b = requestSend.SendUserZan(videoid,shortData.usersid.get());
                        if(b)
                        {
                            int z = Integer.valueOf( shortData.zannumbe.get());
                            shortData.zannumbe.set(String.valueOf(z+1));
                        }
                    }
                }.start();
            }
        });
        //提交评论
        editText = view.findViewById(R.id.text);
        ImageView sendimg = view.findViewById(R.id.sendbtn);
        //提交评论
        sendimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(attribute.getToken()==null||attribute.getUID()==null)
                {
                    Intent intent = new Intent();
                    intent.setAction("sign");
                    startActivity(intent);
                    return;
                }
                String text = editText.getText().toString();
                if(text.isEmpty())
                {
                    Toast.makeText(getContext(),"内容不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                String ss = text.replace(" ","");
                if(ss.length()<1)
                {
                    Toast.makeText(getContext(),"内容不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                new Thread()
                {
                    @Override
                    public void run() {
                        RequestSend send = new RequestSend(getContext());
                        boolean b = send.SendAssess(videoid,attribute.getUID(),text);
                        Message message = new Message();
                        message.what = 1006;
                        message.obj = b;
                        handler.sendMessage(message);
                    }
                }.start();
            }
        });
    }

    //更新UI
    Handler handler = new Handler(Looper.getMainLooper())
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if(msg.what==1000)
            {
                commentAdapter.notifyDataSetChanged();
                new GridViewHeight(FBB.gridview,3);
                return;
            }
            if(msg.what == 1002)
            {
                viptv.setVisibility(View.INVISIBLE);

                String url = (String) msg.obj;
                playerVideo.Playrelease();
                playerVideo.setPlayurl(url);
                playerVideo.loadVideo();
                return;
            }
            if (msg.what == 1006)
            {
                boolean bol = (boolean) msg.obj;
                if(bol)
                {
                    Toast.makeText(getContext(),"评价成功,审核后显示",Toast.LENGTH_SHORT).show();
                    editText.setText(null);
                }else {
                    Toast.makeText(getContext(),"评价失败。",Toast.LENGTH_SHORT).show();
                }
                return;
            }

        }
    };
}